﻿using Andong.Model;
using AnDongBoard.Comm;
using NewAndong.Business;
using NewAndong.Model;
using Newtonsoft.Json;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnDongBoard
{
    public partial class Form1 : Form
    {
        private ConcurrentDictionary<int,UIButton> BtnDictionary = new ConcurrentDictionary<int,UIButton>();
        private SignalLampDirectionBLL signalLampDirectionBLL = new SignalLampDirectionBLL();
        private string Name;
        private bool NatStatus = false;
        private CancellationTokenSource cancel_ipPing;
        private String IP = "192.168.1.250";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                //this.WindowState = FormWindowState.Normal;
            }
            else
            {
                //全屏
                this.WindowState = FormWindowState.Maximized;
            }

            Name = ConfigurationManager.AppSettings["app_key"].ToString();
            IP = ConfigurationManager.AppSettings["app_serviceIp"].ToString();

            btnExit.SetStyle(UIStyle.Red);

            btnNat.Enabled = false;
            btnNat.SetStyle(UIStyle.Blue);
            btnNat.Text = "网络检查...";
            btnNat.FillDisableColor = btnNat.FillColor;
            btnNat.ForeDisableColor = btnNat.ForeColor;

            IpPing();

            cancel_ipPing = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                IpPingTask();
            }, cancel_ipPing.Token);

            uiButton1.Enabled = false;
            uiButton2.Enabled = false;
            uiButton3.Enabled = false;

            uiButton1.SetStyle(UIStyle.Blue);
            uiButton2.SetStyle(UIStyle.Green);
            uiButton3.SetStyle(UIStyle.Red);

            uiButton1.FillDisableColor = uiButton1.FillColor;
            uiButton2.FillDisableColor = uiButton2.FillColor;
            uiButton3.FillDisableColor = uiButton3.FillColor;

            uiButton1.ForeDisableColor = uiButton1.ForeColor;
            uiButton2.ForeDisableColor = uiButton2.ForeColor;
            uiButton3.ForeDisableColor = uiButton3.ForeColor;

            uiPanel2.FillColor = Color.LightGray;

            BtnDictionary.TryAdd(1, btn01);
            BtnDictionary.TryAdd(2, btn02);
            BtnDictionary.TryAdd(3, btn03);
            BtnDictionary.TryAdd(4, btn04);
            BtnDictionary.TryAdd(5, btn05);
            BtnDictionary.TryAdd(6, btn06);
            BtnDictionary.TryAdd(7, btn07);
            BtnDictionary.TryAdd(8, btn08);
            BtnDictionary.TryAdd(9, btn09);
            BtnDictionary.TryAdd(10, btn10);
            BtnDictionary.TryAdd(11, btn11);
            BtnDictionary.TryAdd(12, btn12);
            BtnDictionary.TryAdd(13, btn13);
            BtnDictionary.TryAdd(14, btn14);
            BtnDictionary.TryAdd(15, btn15);
            BtnDictionary.TryAdd(16, btn16);

            if(NatStatus)
            {
                var list = signalLampDirectionBLL.GetModelList();
                var names = list.Select(x => x.LampDescription).ToArray();
                names = names.Distinct().ToArray();

                uiComboBox1.FillColor = Color.DeepSkyBlue;
                uiComboBox1.DataSource = names;
                uiComboBox1.SelectedItem = Name;
                uiComboBox1.Refresh();
            }else
            {
                if (UIMessageDialog.ShowMessageDialog("网络检测异常，请检查网络再重新打开！", UILocalize.AskTitle, true, UIStyle.Red, true, false))
                {
                    cancel_ipPing.Cancel();
                    Thread.Sleep(500);
                    this.Close();
                }
                else
                {

                }
            }

            UiUpdate(Name);

            this.timer1.Enabled = false;
            this.timer1.Interval = 500;
            this.timer1.Start();

        }

        public void IpPingTask()
        {
            while (true)
            {
                if (cancel_ipPing.Token.IsCancellationRequested)
                {
                    cancel_ipPing.Dispose();
                    break;
                }
                IpPing();
                Thread.Sleep(20000);
            }
        }

        public void IpPing()
        {
            var result = PublicHelper.PingIp(IP);
            if (result)
            {
                NatStatus = true;
                this.Invoke(new MethodInvoker(() =>
                {
                    btnNat.Style = UIStyle.Green;
                    btnNat.Text = "网络正常";
                    btnNat.FillDisableColor = btnNat.FillColor;
                    btnNat.ForeDisableColor = btnNat.ForeColor;
                }));
            }
            else
            {
                NatStatus = false;
                this.Invoke(new MethodInvoker(() =>
                {
                    btnNat.Style = UIStyle.Red;
                    btnNat.Text = "网络异常";
                    btnNat.FillDisableColor = btnNat.FillColor;
                    btnNat.ForeDisableColor = btnNat.ForeColor;
                }));
            }
        }

        public void UiUpdate(string typeName, bool isRefreshVisible = true)
        {
            if (!NatStatus)
                return;

            if (isRefreshVisible)
            {
                foreach (var item in BtnDictionary)
                {
                    item.Value.Visible = false;
                }
            }

            var list = signalLampDirectionBLL.GetModelByTypeName(typeName);
            
            if (list != null && list.Count > 0)
            {
                for (int i = 1; i <= list.Count(); i++)
                {
                    UIButton btn;
                    var result = BtnDictionary.TryGetValue(i, out btn);
                    if (result)
                    {
                        if (isRefreshVisible)
                        {
                            btn.Visible = true;
                            btn.Text = list[i - 1].LampName;
                        }
                        if (list[i - 1].Status == 1)
                        {
                            btn.SetStyle(UIStyle.Red);
                        }
                        else if (list[i - 1].Status == 2)
                        {
                            btn.SetStyle(UIStyle.Blue);
                        }
                        else
                        {
                            btn.SetStyle(UIStyle.Green);
                        }
                    }
                }
            }
        }

        bool isFirst = true;
        private void uiComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(isFirst)
            {
                isFirst = false;
                return;
            }

            var value = uiComboBox1.SelectedValue;
            if (value == null)
                return;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection app = config.AppSettings; 
            app.Settings["app_key"].Value = value.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            Name = value.ToString();
            UiUpdate(value.ToString());
        }

        private void btn_Click(object sender, EventArgs e)
        {
            UIButton btn = sender as UIButton;
            if (btn.Style == UIStyle.Red || btn.Style == UIStyle.Blue)
            {
                btn.Style = UIStyle.Green;
                signalLampDirectionBLL.SetModel(Name, btn.Text);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UiUpdate(Name, false);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (UIMessageDialog.ShowMessageDialog("确定要退出系统吗？", UILocalize.AskTitle, true, UIStyle.Red, true, false))
            {
                this.timer1.Stop();
                cancel_ipPing.Cancel();
                this.Close();
            }
            else
            {

            }
        }

    }
}
